import React, { useState, useRef } from 'react';
import { Button, message, Upload, Tooltip } from 'antd';
import { PlayCircleOutlined, UploadOutlined, DeleteOutlined } from '@ant-design/icons';
import { debounce } from 'lodash';
import { v4 as uuidv4 } from 'uuid';
import { requestUploadFile } from 'admin/servers/servers';
import './style.scss';
interface Props {
  /**上传文件夹id */
  fileId: number;
  /**初始数据上屏显示 */
  initData: object;
  /**文件显示的名称 */
  nameStr?: string;
  /**是否支持上传,默认为true,支持*/
  upload?: boolean;
  /**是否支持在线录音,默认为true,支持 */
  record?: boolean;
  /**成功回调 */
  callback: (obj: any) => void;
}
/**文件播放控件：默认支持：播放，删除，重传 */
export const PlayFile: React.FC<Props> = ({
  fileId,
  initData,
  nameStr = '音频文件',
  upload = true,
  record = true,
  callback,
}) => {
  /**录音播放-ref */
  const audioRef = useRef<any>(undefined);
  // 是否正在上传
  const [uploading, setUploading] = useState<boolean>(false);
  // 上传文件
  const [uploadFile, setUploadFile] = useState<any>(undefined);
  // 上传文件，播放地址
  const [filePath, setFilePath] = useState<string>('');
  // 上传状态：0-上传前，1-上传完成，2-上传错误
  const [step, setStep] = useState(0);
  /**
   * 上传前校验
   */
  const beforeUpload = (file: any): boolean => {
    const fileName = file.name.split('.');
    const type = file.type;
    const isWav = (type && type.indexOf('wav') > -1) || fileName[fileName.length - 1] === 'wav';

    const isLt50M = file.size / 1024 / 1024 < 50;
    if (!isWav) {
      message.error('请上传wav文件（只支持wav格式）!');
      return false;
    }
    if (!isLt50M) {
      message.error('文件大小超过50M!');
      return false;
    }
    setUploadFile(file);
    return true;
  };
  /**
   * 执行上传
   */
  const handleUpload = () => {
    setStep(0);
    if (uploading) return false;
    setUploading(true);
    const formData = new FormData();
    const uuid = uuidv4();
    const uploadFilePath = `/transfer_manual_wait_sound/${fileId}/${uuid}.wav`;
    setFilePath(uploadFilePath);
    formData.append('file', uploadFile);
    formData.append('filePath', uploadFilePath);
    console.log('通用上传组件****开始上传', uploadFile, uploadFilePath);
    // 接口
    requestUploadFile(formData)
      .then(res => {
        if (res.code === 0) {
          setUploading(false);
          message.success('上传成功!');
          setStep(1);
          callback({
            // 时分秒
            fileName: nameStr + '.wav',
            filePath: uploadFilePath,
          });
        } else {
          setStep(2);
          message.error(`${res.tips}(错误码: ${res.code})`);
        }
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
        setUploading(false);
        setStep(2);
      });
  };
  /**
   * 删除
   */
  const handleDelete = () => {
    setStep(0);
    setFilePath('');
    setUploading(false);
    callback({
      fileName: undefined,
      filePath: undefined,
    });
  };
  /**
   * 播放
   */
  const handlePlay = (soundUrl: any) => {
    // 当前存在正在播放的录音，直接切换播放地址
    console.log('即将播放：', soundUrl);
    // 时间戳，防止一直播放的是第一段音频
    const envpath = process.env.REACT_APP_API_URL || '';
    const url = envpath + soundUrl + '?timestamp=' + new Date().getTime();
    console.log(url, '789');
    if (!audioRef.current) {
      // 当前没有正在播放的录音
      audioRef.current = new Audio();
      // 绑定-播放暂停事件
      audioRef.current.onpause = () => {
        // 清除-状态
        console.log('播放暂停');
      };
      // 绑定-播放结束事件
      audioRef.current.onended = () => {
        message.info('播放结束');
        clearPlayings();
      };
      // 播放出错
      audioRef.current.onerror = () => {
        message.error('抱歉，播放出错了，请联系管理员~');
        clearPlayings();
      };
    }
    // 暂停播放
    audioRef.current.pause();
    // 切url--开始播放--最后的语音
    audioRef.current.src = url;
    // 开始播放
    audioRef.current.play();
    // 更新播放状态
    // const arr = [...soundRecord];
    // arr.map((item: any) => {
    //   if (item.soundRecordId === id) {
    //     item.playing = true;
    //   } else {
    //     item.playing = false;
    //   }
    //   return null;
    // });
    // setSoundRecord(arr);
  };
  /**
   * 清空上传中数组，清空上传状态
   */
  function clearPlayings() {
    audioRef.current = undefined;
  }
  return (
    <div className="upload-wrap">
      {/* 1-本地上传 */}
      {upload && (
        <Upload
          name="file"
          accept="audio/wav"
          showUploadList={false}
          multiple={false}
          beforeUpload={beforeUpload}
          customRequest={handleUpload}
        >
          <Button type="primary" loading={uploading}>
            本地上传
          </Button>
        </Upload>
      )}
      {/* 2-录制上传 */}
      {record && (
        <Button
          style={{ marginLeft: 10 }}
          type="primary"
          onClick={() => {
            console.log('打开在线录制弹窗');
            message.info('正在开发中，暂不支持！');
          }}
        >
          在线录制
        </Button>
      )}
      <div className="file-tip">*仅支持wav类型文件</div>
      {/* 文件播放、删除和重传 */}
      <div className={'upload-step_' + step}>
        <div className="line-wrap">
          <span className="file-name">{nameStr}.wav</span>
          <Tooltip className="play" placement="top" title="播放">
            <Button
              type="link"
              icon={<PlayCircleOutlined />}
              onClick={debounce(() => {
                handlePlay(filePath);
              }, 700)}
            ></Button>
          </Tooltip>
          <Tooltip className="retry" placement="top" title="重传">
            <Button
              type="link"
              icon={<UploadOutlined />}
              onClick={debounce(() => {
                handleUpload();
              }, 700)}
            ></Button>
          </Tooltip>
          <Tooltip className="delete" placement="top" title="删除">
            <Button
              type="link"
              icon={<DeleteOutlined />}
              onClick={debounce(() => {
                handleDelete();
              }, 700)}
            ></Button>
          </Tooltip>
        </div>
        <div className="error">上传失败请重试</div>
      </div>
    </div>
  );
};
